package sk.tuke.kephera.examples;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Arrays;

import sk.tuke.kephera.connector.KepheraMsg;

import com.fasterxml.jackson.databind.ObjectMapper;

public class MainSimpleCall {

    public static void main(String[] args) throws IOException {
        new MainSimpleCall().sendOnlyStringJson();
//        new MainSimpleCall().sendByObjectJson();
    }

    private void sendOnlyStringJson() throws SocketException, UnknownHostException, IOException {

        //otevreni UDP komunikace
        DatagramSocket socket = new DatagramSocket();
        //adresa prijemce, bud konkretni nebo 255.255.255.255 pro bradcast (vsem)
        InetAddress receiverAddress = InetAddress.getByName("255.255.255.255"); //broadcasting adress
        // port na kterem posloucha receiver (kephera)
        int port = 5002;

        String txtData = "{ \"to\": [ \"gripper@3\" ], \"from\": \"operator@PC\", \"type\": 1, \"body\": { \"rameno\": \"0\" } }";

        //novy UDP paket
        DatagramPacket packet = new DatagramPacket(txtData.getBytes(), txtData.getBytes().length, receiverAddress, port);

        //odeslani paketu prez soket
        socket.send(packet);

        //uzavreni soketu a ukonceni komunikace
        socket.close();
    }

    private void sendByObjectJson() throws IOException {
        ObjectMapper jacksonMapper = new ObjectMapper();

        DatagramSocket socket = new DatagramSocket();
        InetAddress address = InetAddress.getByName("255.255.255.255"); //broadcasting adress

        //objektova reprezentace JSON
        KepheraMsg dotaz = new KepheraMsg();
        dotaz.setType(55);
        dotaz.setFrom("mar@pc");
        dotaz.setTo(Arrays.asList("gripper@3"));
        dotaz.getBody().put("rameno", "500");
        String txtData = fixEndOfJson(jacksonMapper.writeValueAsString(dotaz));
        System.out.println(txtData);

//        JsonProtocol odpoved = jacksonMapper.readValue(txtData, JsonProtocol.class);
//        System.out.println(odpoved);

        //zbytek stejny
        DatagramPacket packet = new DatagramPacket(txtData.getBytes(), txtData.getBytes().length, address, 5002);
        socket.send(packet);
        socket.close();
        System.out.println("data send");
    }

    /**
     * Opravy ze na konci je mezera mezi zavorkami, protoze to ma patrik na TVRDO kontrolovane ve zdorjaku, az to odstrani neni potreba
     * @param txtData
     * @return
     */
    private String fixEndOfJson(String txtData) {
        String f = txtData.substring(0, txtData.lastIndexOf("}}"));
        return f.concat("} }");
    }
}

// "{\"to\": [\"gripper@3\"], \"from\":\"mar@PC\", \"type\":100, \"body\": {\"dopredu\": \"500000\"} }"
